<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">

      <el-form-item label="车名" prop="value">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="状态" prop="value">
          <el-select v-model="queryParams.status" placeholder="请选择">
            <el-option label="全部"    value=""></el-option>
            <el-option label="待使用" :value="0"></el-option>
            <el-option label="运行中" :value="1"></el-option>
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
        <el-button
          v-hasPermi="['huishou:recoveryVehicle:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList"  >
      <el-table-column label="编号" align="center" prop="vehicleNo" />

      <el-table-column label="车名" align="center" prop="name" />
      <el-table-column label="简介" align="center" prop="remark" />
      <el-table-column label="图片" align="center" prop="imgUrl">
        <template slot-scope="scope">
          <img :src="scope.row.imgUrl" style="width: 60px;height: 60px;" alt="">
        </template>
      </el-table-column>

      <el-table-column label="回收员ID" align="center" prop="riderId" />
      <el-table-column label="车牌号" align="center" prop="plateNum" />
      <el-table-column label="车架号" align="center" prop="vinNo" />
      <el-table-column label="载重(吨)" align="center" prop="weightMax" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="状态" align="center" prop="status" />

      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="更新时间" align="center" prop="updateTime" />

      <el-table-column label="操作" align="center" class-name="small-padding" width="220">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['huishou:recoveryVehicle:edit']"
            size="mini"
            type="sucess"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['huishou:recoveryVehicle:remove']"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改推荐管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="编号">
            <el-input v-model="form.vehicleNo" placeholder="请输入编号" clearable  />
        </el-form-item>
        <el-form-item label="车名">
            <el-input v-model="form.name" placeholder="请输入名称" clearable  />
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl">
          <image-upload v-model="imgjson" :limit="1" value-type="json" />
        </el-form-item>
        <el-form-item label="简介">
            <el-input v-model="form.remark" placeholder="请输入简介" clearable  />
        </el-form-item>
        <el-form-item label="状态" v-if="form.id">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option label="待使用" :value="0"></el-option>
            <el-option label="运行中" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属回收员">
          <el-select v-model="form.riderId" placeholder="请选择">
            <el-option
              v-for="item in riderlist"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号">
            <el-input v-model="form.plateNum" placeholder="请输入" clearable  />
        </el-form-item>
        <el-form-item label="车架号">
            <el-input v-model="form.vinNo" placeholder="请输入" clearable  />
        </el-form-item>
        <el-form-item label="载重(吨)">
            <el-input v-model="form.weightMax" placeholder="请输入" clearable  />
        </el-form-item>
        <!-- <el-form-item label="经度">
            <el-input v-model="form.longitude" placeholder="请输入" clearable  />
        </el-form-item>
        <el-form-item label="纬度">
            <el-input v-model="form.latitude" placeholder="请输入" clearable  />
        </el-form-item>
        <el-form-item label="地图选点">
          <el-button type="primary" style="margin-left: 10px;width:120px" @click="parse">解析</el-button>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="modalMap" :visible.sync="modalMap" title="上传经纬度" append-to-body width="60%">
      <iframe
        id="mapPage"
        :src="keyUrl"
        width="100%"
        height="600px"
        frameborder="0"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listCar, addCar, updateCar, delCar } from '@/api/getdata/getdata'
import { listRider } from '@/api/rider/rider'
import { querBasic } from '@/api/basic'

export default {
  name: 'Car',
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // // 选中数组
      // ids: [],
      // // 非单个禁用
      // single: true,
      // // 非多个禁用
      // multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 推荐管理表格数据
      dataList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // id: [
        //   { required: true, message: '不能为空', trigger: 'blur' }
        // ],
        // spuId: [
        //   { required: true, message: '商品id不能为空', trigger: 'blur' }
        // ],

      },
      props: {
        multiple: true,
        value: 'id'
      },
      options: [],
      imgjson: null,
      riderlist: [],
      mapKey: '',
      keyUrl: '',
      modalMap: false,
      qrcode: '',
      flagClick: false

    }
  },
  async created() {
    this.getList()
    this.getRiderList()
    await querBasic({ key: 'mapKey' }).then(res => {
      this.mapKey = res.msg
      this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=${this.mapKey}&referer=myapp`
    })
  },
  mounted() {
    window.addEventListener('message', function(event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data
      if (loc && loc.module === 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.parent.selectAdderss(loc)
      }
    }, false)
    window.selectAdderss = this.selectAdderss
  },
  methods: {
    selectAdderss(data) {
      if (this.flagClick) {
        this.form.litude = data.latlng.lng + ',' + data.latlng.lat
        this.modalMap = false
        this.flagClick = false
        this.form.latitude = data.latlng.lat
        this.form.longitude = data.latlng.lng
        console.log(data, 'datadata')
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listCar(this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    getRiderList() {
      this.loading = true
      listRider({ pageNum: 1, pageSize: 100 }).then(response => {
        this.riderlist = response.rows
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        status: 0
      }
      this.imgjson = null
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // /** 重置按钮操作 */
    // resetQuery() {
    //   this.resetForm('queryForm')
    //   this.handleQuery()
    // },
    // // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id)
    //   this.single = selection.length !== 1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '创建'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.loading = true
      this.reset()
      this.form = row
      const obj = {
        url: row.imgUrl,
        ossId: null
      }
      this.imgjson = JSON.stringify([obj])
      console.log(this.form.imgUrl, ' this.form.imgUrl')
      this.open = true
      this.title = '修改'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          // <el-image :src="JSON.parse(row.imgUrl)[0].url" />
          if (this.imgjson) {
            this.form.imgUrl = JSON.parse(this.imgjson)[0].url
          }
          if (this.form.id != null) {
            updateCar(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            addCar({ ...this.form }).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          }
        }
      })
    },
    getProductIds(ids) {
      const arr = []
      for (let i = 0; i < ids.length; i++) {
        const els = ids[i]
        arr.push(els[els.length - 1])
      }
      console.log(arr)
      return arr
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除？').then(() => {
        this.loading = true
        return delCar(ids)
      }).then(() => {
        this.loading = false
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      }).finally(() => {
        this.loading = false
      })
    },
    parse() {
      this.onSearch('')
    },
    onSearch(address) {
      this.flagClick = true

      this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1', {
        key: this.mapKey,
        address: '安徽省滁州市琅琊区',
        output: 'jsonp'
      }).then(res => {
        if (res.status !== 0) {
          this.$message.warning(res.message)
          return
        }
        const addressStr = res.result.location.lng + ',' + res.result.location.lat
        this.keyUrl += `&coord= ` + addressStr
        this.modalMap = true
        this.form.latitude = res.result.location.lat
        this.form.longitude = res.result.location.lng
      })
    }

  }
}
</script>
